<script setup lang="ts">
import TitleGroup from "@/components/FormRowTitle/index.vue";
import { ElMessageBox, ElNotification } from "element-plus";
import { RefreshLeft, Search, Plus, Grid } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import {
  getTradeRetailPlan,
  addTradeRetailPlan,
  editTradeRetailPlan,
  delTradeRetailPlan
} from "@/api/tradeRetailPlan";
import { useRouter } from "vue-router";
const router = useRouter();
const statusDict = [
  {
    value: 0,
    label: "未生效"
  },
  {
    value: 1,
    label: "生效"
  },
  {
    value: 2,
    label: "已失效"
  }
];
const dictFormat = (key, value, data) => {
  if (value || value === 0) {
    let item = data.find(i => parseInt(i.value) === parseInt(value));
    if (item) {
      return item.label;
    } else {
      return "";
    }
  } else {
    return "";
  }
};
const dictList = reactive({
  data: {
    status: statusDict
  }
});
const loading = ref(false);
const queryForm = reactive({
  data: {
    name: undefined
  }
});
const tableColums = [
  {
    id: 1,
    label: "套餐名称",
    key: "name",
    prop: "name",
    width: "300px",
    align: "center"
  },
  {
    id: 2,
    label: "套餐生效年",
    key: "years",
    prop: "years",
    width: "200px",
    align: "center"
  },
  {
    id: 3,
    label: "套餐持续月份",
    key: "month",
    prop: "month",
    width: "200px",
    align: "center"
  },
  {
    id: 4,
    label: "申报电量偏差",
    key: "electricDeviation",
    prop: "electricDeviation",
    width: "200px",
    align: "center"
  },
  {
    id: 5,
    label: "免考核机制",
    key: "nonExam",
    prop: "nonExam",
    width: "200px",
    align: "center"
  },
  {
    id: 6,
    label: "当前状态", //  0:未生效 1:生效 2:已失效
    key: "status",
    prop: "status",
    width: "200px",
    align: "center"
  },
  {
    id: 7,
    label: "适用对象",
    key: "applicableObject",
    prop: "applicableObject",
    width: "200px",
    align: "center"
  },
  {
    id: 8,
    label: "解约条款",
    key: "cancellationClause",
    prop: "cancellationClause",
    width: "200px",
    align: "center"
  }
];
const search = async () => {
  pageObj.data.currentPage = 1;
  let res = await getData();
  tableData.data = res.content;
  pageObj.data.total = res.totalElements;
};
const getData = () => {
  loading.value = true;
  return new Promise<any>(async (resolve, reject) => {
    let data = await getTradeRetailPlan({
      current: pageObj.data.currentPage,
      size: pageObj.data.pageSize,
      ...queryForm.data
    });
    loading.value = false;
    resolve(data);
  });
};

const dataDelRow = async row => {
  await delTradeRetailPlan([row.id]);
};
const resetQuery = () => {
  queryForm.data = {
    name: undefined
  };
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = async () => {
  let res = await getData();
  tableData.data = res.content;
  pageObj.data.total = res.totalElements;
};
const tableData = reactive({
  data: []
});
const status = ref("add");
const edit = row => {
  // title.value = "编辑零售套餐";
  // addDialog.value = true;
  status.value = "edit";
  // form.data = JSON.parse(JSON.stringify(row));
  router.push(
    `/electricitySalesManagement/tradeRetailPlan/handle/edit/${row.id}`
  );
};
const look = row => {
  // title.value = "查看零售套餐";
  // addDialog.value = true;
  status.value = "look";
  // form.data = JSON.parse(JSON.stringify(row));
  router.push(
    `/electricitySalesManagement/tradeRetailPlan/handle/look/${row.id}`
  );
};
const form = reactive({
  data: {
    name: undefined,
    years: undefined,
    month: undefined,
    plusDeviationExemScale: undefined,
    plusDeviationExamRate: undefined,
    minusDeviationExemScale: undefined,
    minusDeviationExamRate: undefined,
    electricDeviation: undefined,
    nonExam: undefined,
    applicableObject: undefined,
    cancellationClause: undefined,
    status: 1
  },
  rules: {
    name: [{ required: true, message: "请输入套餐名称", trigger: "blur" }],
    years: [{ required: true, message: "请输入套餐生效年", trigger: "blur" }],
    month: [{ required: true, message: "请输入套餐持续月份", trigger: "blur" }],
    plusDeviationExemScale: [
      { required: true, message: "请输入正偏差免考比例", trigger: "blur" }
    ],
    plusDeviationExamRate: [
      { required: true, message: "请输入正偏差考核费率", trigger: "blur" }
    ],
    minusDeviationExemScale: [
      { required: true, message: "请输入负偏差免考比例", trigger: "blur" }
    ],
    minusDeviationExamRate: [
      { required: true, message: "请输入负偏差考核费率", trigger: "blur" }
    ],
    electricDeviation: [
      { required: true, message: "请输入申报电量偏差", trigger: "blur" }
    ],
    nonExam: [{ required: true, message: "请输入免考核机制", trigger: "blur" }],
    applicableObject: [
      { required: true, message: "请输入适用对象", trigger: "blur" }
    ],
    cancellationClause: [
      { required: true, message: "请输入解约条款", trigger: "blur" }
    ],
    status: [{ required: true, message: "请选择当前状态", trigger: "change" }]
  }
});
const del = row => {
  ElMessageBox.confirm("是否确认删除该零售套餐?", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await dataDelRow(row);
    search();
    ElNotification({
      title: "系统提示",
      message: "删除成功",
      type: "success"
    });
  });
};
const formRules = ref(null);
const addDialog = ref(false);
const title = ref("添加");

const add = () => {
  title.value = "创建详情";
  // addDialog.value = true;
  status.value = "add";
  router.push(`/electricitySalesManagement/tradeRetailPlan/handle/add/null`);
};
const cancel = () => {
  form.data = {
    name: undefined,
    years: undefined,
    month: undefined,
    plusDeviationExemScale: undefined,
    plusDeviationExamRate: undefined,
    minusDeviationExemScale: undefined,
    minusDeviationExamRate: undefined,
    electricDeviation: undefined,
    nonExam: undefined,
    applicableObject: undefined,
    cancellationClause: undefined,
    status: 1
  };
  setTimeout(() => {
    formRules.value && formRules.value.clearValidate();
    addDialog.value = false;
  }, 0);
};
const subLoading = ref(false);
const submit = () => {
  subLoading.value = true;
  formRules.value.validate(async valid => {
    if (valid) {
      if (status.value === "add") {
        await addTradeRetailPlan({
          ...form.data
        });
        ElNotification({
          title: "系统提示",
          message: "零售套餐创建成功",
          type: "success"
        });
      } else {
        await editTradeRetailPlan({
          ...form.data
        });
        ElNotification({
          title: "系统提示",
          message: "零售套餐修改成功",
          type: "success"
        });
      }
      search();
      cancel();
    }
    subLoading.value = false;
  });
};
const init = () => {
  search();
};
const beforeClose = async d => {
  await cancel();
  d();
};
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);
const defaultColums = reactive({
  data: []
});
const colums = reactive({
  data: []
});
onMounted(() => {
  defaultColums.data = tableColums;
  colums.data = tableColums;
  init();
  checkedCities.value = colums.data.map(item => item.prop);
});
const queryShow = ref(true);
const getList = () => {
  search();
};

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-row v-if="queryShow">
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-input
              v-model="queryForm.data.name"
              placeholder="请输入套餐名称"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >查询</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="w-full flex justify-between mb-[10px]">
        <div class="buttons flex align-center">
          <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
          <!--          <el-button-->
          <!--            type="success"-->
          <!--            :icon="Edit"-->
          <!--            :disabled="!(multipleSelection.length === 1)"-->
          <!--            @click="editSelect"-->
          <!--          >修改</el-button-->
          <!--          >-->
          <!--          <el-button-->
          <!--            type="danger"-->
          <!--            :icon="Delete"-->
          <!--            :disabled="!multipleSelection.length"-->
          <!--            @click="delSelect"-->
          <!--          >删除</el-button-->
          <!--          >-->
          <!--            <el-button type="warning" :icon="Download" @click="exportData"-->
          <!--              >导出</el-button-->
          <!--            >-->
        </div>
        <div class="settings">
          <el-button-group class="ml-4">
            <el-button
              type="primary"
              :icon="Search"
              @click="queryShow = !queryShow"
            />
            <el-button type="primary" :icon="RefreshLeft" @click="getList" />
            <el-popover placement="bottom" :width="200" trigger="click">
              <template #reference>
                <el-button type="primary" :icon="Grid" />
              </template>
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <div class="group-box w-full max-h-[240px] overflow-y-auto">
                <el-checkbox-group
                  v-model="checkedCities"
                  class="columns-show-group"
                  @change="handleCheckedCitiesChange"
                >
                  <el-checkbox
                    v-for="item in defaultColums.data"
                    :key="item.prop"
                    :label="item.prop"
                    >{{ item.label }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
            </el-popover>
          </el-button-group>
        </div>
      </div>
      <div class="w-full">
        <el-table :data="tableData.data" width="100%">
          <el-table-column
            v-for="item in colums.data"
            :key="item.id"
            :label="item.label"
            :prop="item.key"
            :width="item.width"
            :align="item.align"
          >
            <template
              v-if="['status'].indexOf(item.prop) > -1"
              #default="scope"
            >
              <span>{{
                dictFormat(
                  item.prop,
                  scope.row[item.prop],
                  dictList.data[item.prop]
                )
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="240px"
            :fixed="'right'"
            label="操作"
            align="center"
          >
            <template #default="scope">
              <el-button text type="primary" @click="look(scope.row)"
                >查看</el-button
              >
              <el-button text type="primary" @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-button text type="primary" @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page w-full mt-[10px]">
        <el-pagination
          v-model:current-page="pageObj.data.currentPage"
          v-model:page-size="pageObj.data.pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageObj.data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="addDialog"
      :before-close="beforeClose"
      :title="title"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="w-full">
        <el-form
          ref="formRules"
          class="display-block"
          :model="form.data"
          label-width="160px"
          :rules="form.rules"
          :disabled="status === 'look'"
        >
          <TitleGroup title="基础信息">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="套餐名称" prop="name">
                  <el-input v-model="form.data.name" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="套餐生效年" prop="years">
                  <el-input-number
                    v-model="form.data.years"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="套餐持续月份" prop="month">
                  <el-input-number
                    v-model="form.data.month"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申报电量偏差" prop="electricDeviation">
                  <el-input
                    v-model="form.data.electricDeviation"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="正偏差免考比例"
                  prop="plusDeviationExemScale"
                >
                  <el-input-number
                    v-model="form.data.plusDeviationExemScale"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="正偏差考核费率"
                  prop="plusDeviationExamRate"
                >
                  <el-input-number
                    v-model="form.data.plusDeviationExamRate"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="负偏差免考比例"
                  prop="minusDeviationExemScale"
                >
                  <el-input-number
                    v-model="form.data.minusDeviationExemScale"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="负偏差考核费率"
                  prop="minusDeviationExamRate"
                >
                  <el-input-number
                    v-model="form.data.minusDeviationExamRate"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="免考核机制" prop="nonExam">
                  <el-input v-model="form.data.nonExam" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="适用对象" prop="applicableObject">
                  <el-input
                    v-model="form.data.applicableObject"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="解约条款" prop="cancellationClause">
                  <el-input
                    v-model="form.data.cancellationClause"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="当前状态" prop="status">
                  <el-select v-model="form.data.status" placeholder="请选择">
                    <el-option
                      v-for="item in dictList.data.status"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </TitleGroup>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="status === 'look'" @click="cancel">关闭</el-button>
          <el-button v-if="status !== 'look'" @click="cancel">取消</el-button>
          <el-button
            v-if="status !== 'look'"
            :loading="subLoading"
            type="primary"
            @click="submit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .demo-tabs {
      display: flex;
      flex: 1;
      flex-direction: column;
      overflow: hidden;

      .el-tabs__content {
        flex: 1;

        .el-tab-pane {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
